package com.kym_club.wechat4j;

import com.kym_club.wechat4j.WechatStartup;
import com.kym_club.wechat4j.core.WechatApiUtil;
import com.kym_club.wechat4j.core.WechatMeta;
import com.kym_club.wechat4j.plugin.MessageListener;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;


/**
 * @PcName: zym
 * @name: keyouming
 * @Date: 2021/4/8 10:11
 * @Description:
 */
@Controller
public class TestController {

    @GetMapping("/test")
    public void test(HttpServletResponse response) {

        String uuid = WechatApiUtil.getUUID();
        final String path = WechatApiUtil.getQrCode(uuid);
        File file = new File(path);
        try {
            byte[] data = File2byte(file);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    WechatMeta meta = WechatStartup.login(uuid);
                    MessageListener listener = new MessageListener(meta);
                    listener.listen();
                }
            }).start();
            ServletOutputStream out = response.getOutputStream();
            out.write(data);
            out.flush();
            file.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public static byte[] File2byte(File tradeFile) {
        byte[] buffer = null;
        try {
            FileInputStream fis = new FileInputStream(tradeFile);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }
}
